#!/bin/bash

# File ID: 43e64d72-d26d-11de-a010-90e6ba3022ac

dev=sdb1
mountp=/media/usb

if [ "$1" = "-l" ]; then
    unset tzval
    shift
else
    tzval="tz=UTC,"
fi
[ -z "$1" ] || dev=$1
[ -z "$2" ] || mountp=$2
[ -d "$mountp/." ] || { mkdir $mountp || { echo mountusb: $mountp: Cannot create directory; exit 1; }; }
opts="-o fmask=0111,uid=sunny,gid=sunny,${tzval}shortname=mixed"

mount | grep /dev/$dev && {
    echo mountusb: Unmounting /dev/$dev
    sudo umount /dev/$dev || { echo mountusb: /dev/$dev: Cannot unmount >&2; exit 1; }
    sleep 2
}

echo "mountusb: Mounting /dev/$dev on $mountp using \"$opts\""
sudo mount /dev/$dev $mountp $opts

# Check for existing /mntopts file in disk root. That file contains mount 
# options used on the command line when mounting.
if [ -e $mountp/mntopts -o -e $mountp/MNTOPTS ]; then
    [ -e $mountp/MNTOPTS ] && mntopts=MNTOPTS
    [ -e $mountp/mntopts ] && mntopts=mntopts
    opts2="`cat $mountp/$mntopts`"
    [ "$opts" = "$opts2" ] && { echo "mountusb: /mntopts contains standard options, remount not necessary"; exit 0; }
    sync
    sleep 3
    sudo umount $mountp
    sync
    echo "mountusb: Remount  /dev/$dev on $mountp using \"$opts2\""
    sudo mount /dev/$dev $mountp $opts2
fi
